import { createRouter, createWebHistory } from 'vue-router'
import Login from '@/components/Login.vue'
import AIChat from '@/components/AIChat.vue'
import KnowledgeManagement from '@/components/KnowledgeManagement.vue'
import SystemManagement from '@/components/SystemManagement.vue'
import ResetPassword from '@/components/ResetPassword.vue'
import ResetPasswordConfirm from '@/components/ResetPasswordConfirm.vue'
import Register from '@/components/Register.vue'
import Dashboard from '@/components/Dashboard.vue'
import Header from '@/components/Header.vue'
import ChangePassword from '@/components/ChangePassword.vue'

const routes = [
  {
    path: '/',
    name: 'Login',
    component: Login,
    meta: {
      requiresAuth: false
    }
  },
  {
    path: '/ai-chat',
    name: 'AIChat',
    component: AIChat,
    meta: {
      requiresAuth: true
    }
  },
  {
    path: '/knowledge-management',
    name: 'KnowledgeManagement',
    component: KnowledgeManagement,
    meta: {
      requiresAuth: true
    }
  },
  {
    path: '/system-management',
    name: 'SystemManagement',
    component: SystemManagement,
    meta: {
      requiresAuth: true
    }
  },
  {
    path: '/reset-password',
    name: 'ResetPassword',
    component: ResetPassword,
    meta: {
      requiresAuth: false
    }
  },
  {
    path: '/reset-password-confirm',
    name: 'ResetPasswordConfirm',
    component: ResetPasswordConfirm,
    meta: {
      requiresAuth: false
    }
  },
  {
    path: '/register',
    name: 'Register',
    component: Register,
    meta: {
      requiresAuth: false
    }
  },
  {
    path: '/dashboard',
    name: 'Dashboard',
    component: Dashboard,
    meta: {
      requiresAuth: true
    }
  },
  {
    path: '/change-password',
    name: 'ChangePassword',
    component: ChangePassword,
    meta: {
      requiresAuth: true
    }
  },
  // 重定向到登录页
  {
    path: '/:pathMatch(.*)*',
    redirect: '/'
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

// 添加路由守卫
router.beforeEach((to, from, next) => {
  // 检查路由是否需要认证
  if (to.meta.requiresAuth) {
    // 获取localStorage中的token
    const token = localStorage.getItem('access_token');
    
    // 如果没有token，重定向到登录页
    if (!token) {
      next('/');
    } else {
      // 检查token是否有效（这里可以添加更复杂的token验证逻辑）
      next();
    }
  } else {
    // 不需要认证的路由，直接通过
    next();
  }
})

export default router